package com.a.lib_ui.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import com.a.lib_ui.R;
import org.jetbrains.annotations.NotNull;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Objects;
/**
 * 日期选择Dialog
 * */
public class CustomDatePickerDialogFragment extends DialogFragment implements DatePicker.OnDateChangedListener, View.OnClickListener {
    public static final String CURRENT_DATE = "datepicker_current_date";
    public static final String START_DATE = "datepicker_start_date";
    public static final String END_DATE = "datepicker_end_date";
    Calendar currentDate;
    Calendar startDate;
    Calendar endDate;
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);

    DatePicker datePicker;
    TextView backButton;
    TextView ensureButton;
    View splitLineV;
    private final String date;

    public CustomDatePickerDialogFragment(String date) {
        this.date = date;
    }


    public static CustomDatePickerDialogFragment newInstance(String date) {
        return new CustomDatePickerDialogFragment(date);
    }

    public CustomDatePickerDialogFragment selectDate(OnSelectedDateListener onSelectedDateListener) {
        this.onSelectedDateListener = onSelectedDateListener;
        return this;
    }

    private int color = R.color.white;

    public CustomDatePickerDialogFragment setTextColor(@ColorInt int color) {
        this.color = color;
        return this;
    }

    @SuppressLint("ResourceAsColor")
    public CustomDatePickerDialogFragment compareDate(TextView tvStart, TextView tvEnd) throws ParseException {//日期顺序不对，字体爆红
        String dateStr = tvStart.getText().toString();
        String dateStr2 = tvEnd.getText().toString();
        Date date1 = sdf.parse(dateStr);
        Date date2 = sdf.parse(dateStr2);
        if (Objects.requireNonNull(date1).getTime() > Objects.requireNonNull(date2).getTime()) {
            tvStart.setTextColor(Color.parseColor("#FF0000"));
            tvEnd.setTextColor(Color.parseColor("#FF0000"));
            Toast.makeText(requireActivity(), "日期有误，请重新选择日期！", Toast.LENGTH_SHORT).show();
        } else {
            tvStart.setTextColor(color);
            tvEnd.setTextColor(color);
        }
        return this;
    }

    public void show(AppCompatActivity activity) {
        super.show(activity.getSupportFragmentManager(), CustomDatePickerDialogFragment.class.getSimpleName());
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCancelable(false);
        Bundle bundle = new Bundle();
        currentDate = Calendar.getInstance();
        currentDate.setTimeInMillis(System.currentTimeMillis());
        if (!Objects.equals(date, "")) {
            currentDate.set(Calendar.YEAR, Integer.parseInt(date.substring(0, 4)));
            currentDate.set(Calendar.MONTH, Integer.parseInt(date.substring(5, 7)) - 1);
            currentDate.set(Calendar.DAY_OF_MONTH, Integer.parseInt(date.substring(8, 10)));
        }
        currentDate.set(Calendar.HOUR_OF_DAY, 0);
        currentDate.set(Calendar.MINUTE, 0);
        currentDate.set(Calendar.SECOND, 0);
        currentDate.set(Calendar.MILLISECOND, 0);
        bundle.putSerializable(CustomDatePickerDialogFragment.CURRENT_DATE, currentDate);
        long MS_OF_A_DAY = 86400000L;
        long start = currentDate.getTimeInMillis() - MS_OF_A_DAY * 1000;
        long end = currentDate.getTimeInMillis() + MS_OF_A_DAY * 30;
        startDate = Calendar.getInstance();
        startDate.setTimeInMillis(start);
        endDate = Calendar.getInstance();
        endDate.setTimeInMillis(end);
        bundle.putSerializable(CustomDatePickerDialogFragment.START_DATE, startDate);
        bundle.putSerializable(CustomDatePickerDialogFragment.END_DATE, endDate);
    }

    @Nullable
    @Override
    public View onCreateView(@NotNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Objects.requireNonNull(getDialog()).requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setDimAmount(0.8f);
        return inflater.inflate(R.layout.core_ui_fragment_date_picker_layout, container, false);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        int style;
        style = R.style.ZZBDatePickerDialogLStyle;
        return new Dialog(getActivity(), style);
    }

    @Override
    public void onViewCreated(@NotNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        datePicker = view.findViewById(R.id.datePickerView);
        backButton = view.findViewById(R.id.back);
        backButton.setOnClickListener(this);
        ensureButton = view.findViewById(R.id.ensure);
        ensureButton.setOnClickListener(this);
        splitLineV = view.findViewById(R.id.splitLineV);
        //bug4:LOLLIPOP和Marshmallow上，使用spinner模式，然后隐藏滚轮，显示日历(spinner模式下的日历没有头部)，日历最底部一排日期被截去部分。所以只能使用calender模式，然后手动隐藏header（系统没有提供隐藏header的api）。
        //如果只要日历部分，隐藏header
        ViewGroup mContainer = (ViewGroup) datePicker.getChildAt(0);
        View header = mContainer.getChildAt(0);
        header.setVisibility(View.GONE);
        //Marshmallow上底部留白太多，减小间距
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) datePicker.getLayoutParams();
        layoutParams.bottomMargin = 10;
        datePicker.setLayoutParams(layoutParams);
        initDatePicker();
    }

    private void initDatePicker() {
        if (datePicker == null) {
            return;
        }
        if (currentDate == null) {
            currentDate = Calendar.getInstance();
            currentDate.setTimeInMillis(System.currentTimeMillis());
        }
        datePicker.init(currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DAY_OF_MONTH), this);
        if (startDate != null) {
            datePicker.setMinDate(startDate.getTimeInMillis());
        }
        if (endDate != null) {
            //bug5:5.1上，maxdate不可选。由于5.0有bug3，所以可能bug5被掩盖了。4.x和6.0+版本没有这个问题。
            //bug5在6.0+上有另一个表现形式：初始化时会触发一次onDateChanged回调。通过源码分析一下原因：init方法只会设置控件当前日期的
            //年月日，而时分秒默认使用现在时间的时分秒，所以当前日期大于>最大日期，执行setMaxDate方法时，就会触发一次onDateChanged回调。
            //同理，setMinDate方法也面临同样的方法。所以设置范围时，MinDate取0时0分0秒，MaxDate取23时59分59秒。
            endDate.set(Calendar.HOUR_OF_DAY, 23);
            endDate.set(Calendar.MINUTE, 59);
            endDate.set(Calendar.SECOND, 59);
            datePicker.setMaxDate(endDate.getTimeInMillis());
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.back) {
            dismiss();
        } else if (id == R.id.ensure) {
            try {
                returnSelectedDateUnderLOLLIPOP();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }


    private void returnSelectedDateUnderLOLLIPOP() throws ParseException {
        //bug3:5.0上超过可选区间的日期依然能选中,所以要手动校验.5.1上已解决，但是为了与5.0保持一致，也采用确定菜单返回日期
        if (onSelectedDateListener != null) {
            String day = datePicker.getDayOfMonth() + "";
            if (day.length() == 1) {
                day = "0" + day;
            }
            String month = (datePicker.getMonth() + 1) + "";
            if (month.length() == 1) {
                month = "0" + month;
            }
            onSelectedDateListener.onSelectedDate(datePicker.getYear() + "-" + month + "-" + day, datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
        }
        dismiss();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        onSelectedDateListener = null;
    }

    public interface OnSelectedDateListener {
        void onSelectedDate(String date, int year, int monthOfYear, int dayOfMonth) throws ParseException;
    }

    OnSelectedDateListener onSelectedDateListener;

    public void setOnSelectedDateListener(OnSelectedDateListener onSelectedDateListener) {
        this.onSelectedDateListener = onSelectedDateListener;
    }

    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        if (onSelectedDateListener != null) {
            String day = dayOfMonth + "";
            if (day.length() == 1) {
                day = "0" + day;
            }
            String month = (monthOfYear + 1) + "";
            if (month.length() == 1) {
                month = "0" + month;
            }
            try {
                onSelectedDateListener.onSelectedDate(year + "-" + month + "-" + day, year, monthOfYear, dayOfMonth);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        dismiss();
    }
}
